package com.feiniu.api.util;

import com.feiniu.api.pojo.HttpClientResponsePojo;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class HttpClientUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final String ENCODING = "utf-8";

    public static HttpClientResponsePojo post(String urlPath, String json) {
        HttpClientResponsePojo response = new HttpClientResponsePojo();
        try {
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("content-type", "application/json");
            urlConnection.setRequestProperty("accept-encoding", "gzip,deflate");

            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            out.write(json);
            out.flush();
            out.close();

            if (urlConnection.getResponseCode() == HttpStatus.SC_OK) {
                InputStream inputStream = urlConnection.getInputStream();

                String responseStr;
                if (urlConnection.getHeaderField("Content-Encoding") != null
                        && urlConnection.getHeaderField("Content-Encoding").toLowerCase().contains("gzip")) {
                    LOGGER.info("*** content encoding contains gzip ***");
                    GZIPInputStream gzipIn = new GZIPInputStream(inputStream);
                    responseStr = IOUtils.toString(gzipIn, ENCODING);
                } else {
                    responseStr = IOUtils.toString(inputStream, ENCODING);
                }

                response.setCode(urlConnection.getResponseCode());
                response.setMessage(responseStr);
            } else {
                response.setCode(urlConnection.getResponseCode());
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setCode(-1);
            response.setMessage(e.getMessage());
        }
        return response;
    }

}
